package com.kmenpin;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientHelper {

    public static String doGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        String strResult = "";
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            int resCode = httpResponse.getStatusLine().getStatusCode();
            if (resCode == 200) {
                strResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                System.out.println(">>> doGet response: " + strResult);
                return strResult;
            } else {
                throw new IOException("got response code: " + resCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
        }
    }
}
